package com.cjl.gateway.filter;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.cjl.utils.common.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwsHeader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author cjl
 * @version v1.0
 * @description TODO
 * @createTime 2023/2/16 10:50
 */
@Slf4j
@Component
public class HostFirstFilter implements GlobalFilter, Ordered {

    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求和响应
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //获取请求路径
        String path = request.getPath().toString();

        //如果是登录/注册操作，直接放行
        if (path.contains("login_auth")) return chain.filter(exchange);

        //获取token
        String token = request.getHeaders().getFirst("token");

        //判断token是否存在
        if (StringUtils.isBlank(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            log.error("未授权身份被拦截-filter1");
            return response.setComplete();
        }

        try {
            //判断token是否有效
            Claims claimsBody = JwtUtil.getClaimsBody(token);
            int flag = JwtUtil.verifyToken(claimsBody);
            if (flag == 1 || flag == 2) {
                log.error("token已过期");
                return response.setComplete();
            }

            Object hostId = claimsBody.get("id");
            //在header中添加新的信息
            ServerHttpRequest serverHttpRequest = request.mutate().headers(
                    httpHeaders -> httpHeaders.add("hostId", hostId + "")
            ).build();
            //重置header
            exchange.mutate().request(serverHttpRequest).build();

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //放行
        return chain.filter(exchange);
    }
}
